<script>
import {ref, reactive, shallowRef} from "vue";
import { ElMessage, ElMessageBox ,ElLoading  } from "element-plus";
import {get_news_info,up_banner_api, delete_news} from "../../api";
import {useRouter} from "vue-router";
import { SERVER_HOST } from "../../config";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import TextEditor from '../../components/TextEditor.vue'

export default {
  name: "newstable",
  components: {Editor, Toolbar ,TextEditor  },
  setup() {
    const router = useRouter();
    const query = reactive({
      page: 0,
      rows: 5,
      id:'',
      books_name:'',
      classify:'',
      press:'',
      book_status:'',
      news_title:'',
      author:'',
      news_type_id:'',
      is_banner:'',
      status:''
    });

    const is_banner = ref(false)
    const tableData = ref([]);
    const pageTotal = ref(0);
    const loadingswith=ref(true)


    const up_banner =()=> {
      console.log('banner')
      up_banner_api(query.is_banner).then((res) => {
        var code = res.code;
        if (code===200){
          ElMessage.success(res.msg);

        }else if(code===401){
          ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
            confirmButtonText: "确定",
            callback: action => {
              sessionStorage.clear()
              localStorage.removeItem("user_name");
              localStorage.removeItem("token");
              console.log('用户信息已清除')
              router.push('/login')
            }
          });
        }else{
          tableData.value = res.data;
          loadingswith.value=false;
        }

      })
    }
    const rowsDtailData = ref('')
    const newsDetalSwitch = ref(false)
    const openNewsDtail=(index,rows)=>{
      newsDetalSwitch.value =true
      // rowsDtailData.value=rows.content
      valueHtml.value=rows.content
    }

    // 获取表格数据
    const getData = () => {
      var startTime= new Date().getTime();
      loadingswith.value=true;
      get_news_info(query).then((res) => {
            var code = res.code;
            if (code===200){
              tableData.value = res.data;
              pageTotal.value = res.total || 0;
              console.log(res.data[0].headline)
              var endTime= new Date().getTime();
              ElMessage.success('请求耗时'+(endTime-startTime)+"ms");
              loadingswith.value=false;
            }else if(code===401){
              ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
                confirmButtonText: "确定",
                callback: action => {
                  sessionStorage.clear()
                  localStorage.removeItem("user_name");
                  localStorage.removeItem("token");
                  console.log('用户信息已清除')
                  router.push('/login')
                }
              });
            }else{
              tableData.value = res.data;
              loadingswith.value=false;
            }

          }

      );

    };
    getData()
    // 查询操作
    const handleSearch = () => {
      query.pageIndex = 1;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.page = val-1;
      getData();
    };

    // 每页显示条数
    const handleSizeChange = (val) => {
      query.rows = val;
      getData();

    };


    const handleClose = ()=>{
      ElMessageBox.confirm("确定要关闭吗？", "提示", {
        type: "warning",
      }).then(() => {
        addVisible.value = false;
      }).catch(() => {
        ElMessage.warning("取消关闭");
      });
    }

    // 删除操作
    const remove_news = (index,row) => {
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        delete_news(form).then((res) => {
          var code = res.code;
          var msg = res.msg;
          if (code===200){
            ElMessage.success(""+msg);
          }else if(code===401){
            ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
              confirmButtonText: "确定",
              callback: action => {
                router.push('/login')
              }
            });
          }else {
            ElMessage.error(''+msg);
          }
        });
        //停留200毫秒后刷新页面数据
        setTimeout(() => {
          getData()
        }, 200);
      }).catch(() => {
        ElMessage.warning("删除取消");
      });
    };


    // 表格编辑时弹窗和保存
    const editVisible = ref(false);
    const addVisible = ref(false);
    let form = reactive({
      id:0,
      title:"",
      headline:"",
      author:"",
      news_type:"",
      content:"",
      status:"",
      is_banner:""
    });




    let idx = -1;
    let fileList= ref([]);
    let imgobj=ref({
      url:""
    })


    const handleEdit = (index, row) => {
      imgobj.url=row.headline;
      fileList.value=[]
      fileList.value.push((imgobj))
      idx = index;
      Object.keys(form).forEach((item) => {
        form[item] = row[item];
      });
      if (form.status===1){
        form.status="正常"
      }else if (form.status===2){
        form.status="下架"
      }
      console.log(form.status)
      editVisible.value = true;
    };
// 获取视口高度
    const screenHeight = window.innerHeight-290;

    const handleAdd = () => {
      form.img=''
      form.commodity_name=''
      form.color=''
      form.sku=''
      form.status=''
      form.commodity_code=''
      form.description=''
      form.price=''
      addVisible.value = true;

      console.log(fileList)
    };




    const msg = () => {
      ElMessage.warning("功能未完善，敬请期待！");
    };
    const handleRemove=() =>{

    };
    const handlePictureCardPreview=(file)=> {
      form.book_image_url=file.response.data.file_url;
    };

    const handleAvatarSuccess=(resource) =>{
      fileList.value=[]
      imgobj.url=resource.data.file_url;
      fileList.value.push((imgobj))
      console.log(imgobj.url)
      form.book_image_url=imgobj.url;
      addForm.book_image_url=imgobj.url;
      console.log(addForm.book_image_url)
    };


    const editstart=(file)=>{
      handleRemove()
    }

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    //  富文本编辑器相关
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')
    const toolbarConfig = {}
    const editorConfig = {
      readOnly : true,
    }
    return {
      query,
      tableData,
      pageTotal,
      editVisible,
      form,
      is_banner,
      fileList,
      addVisible,
      newsDetalSwitch,
      rowsDtailData,
      valueHtml,
      toolbarConfig,
      editorConfig,
      editorRef,
      openNewsDtail,
      handleCreated,
      getData,
      handleAdd,
      handleRemove,
      handleAvatarSuccess,
      handlePictureCardPreview,
      handleSearch,
      handlePageChange,
      handleSizeChange,
      handleEdit,
      msg,
      remove_news,
      up_banner,
      SERVER_HOST,
      screenHeight,
      handleClose,
      mode: 'simple', // 或 'simple'
    };
  }
};
</script>

<template>
    <div>

        <div class="container"  >
            <div class="handle-box" >
              <el-input v-model="query.id" placeholder="新闻Id" clearable class="handle-input mr10"></el-input>
              <el-input v-model="query.news_title" placeholder="新闻标题" clearable class="handle-input mr10"></el-input>
              <el-input v-model="query.author" placeholder="新闻作者" clearable class="handle-input mr10"></el-input>
              <el-select v-model="query.news_type_id" placeholder="新闻类别" clearable class="handle-select mr10">
                <el-option key="1" label="国内" value="1"></el-option>
                <el-option key="2" label="国际" value="2"></el-option>
                <el-option key="3" label="娱乐" value="3"></el-option>
                <el-option key="4" label="军事" value="4"></el-option>
                <el-option key="5" label="体育" value="5"></el-option>
                <el-option key="6" label="科技" value="6"></el-option>
                <el-option key="7" label="财经" value="7"></el-option>
              </el-select>
              <el-select v-model="query.is_banner" placeholder="是否置顶轮播" clearable class="handle-select mr10">
                <el-option key="0" label="非置顶" value="0"></el-option>
                <el-option key="1" label="置顶" value="1"></el-option>
              </el-select>
              <el-select v-model="query.status" placeholder="状态" clearable class="handle-select mr10">
                <el-option key="0" label="正常" value="0"></el-option>
                <el-option key="1" label="下架" value="1"></el-option>
              </el-select>
                <el-button type="primary" icon="el-icon-search" @click="getData">搜索</el-button>
              <el-button type="primary" icon="el-icon-circle-plus-outline" @click="$router.push({name:'news-create'})">发布新闻</el-button>
              <el-button type="danger" icon="el-icon-delete" @click="msg">批量删除</el-button>
            </div>
            <el-table :data="tableData" v-loading="loadingswith"  element-loading-text="拼命加载中..." element-loading-background="rgba(250,250,250,0.97)" border class="table" :height="screenHeight" ref="multipleTable" header-cell-class-name="table-header">
                <el-table-column prop="id" label="新闻id"></el-table-column>
              <el-table-column width="400px" prop="title" label="新闻标题"></el-table-column>
              <el-table-column label="新闻头图" width="150px" align="center">
                <template #default="scope">
                  <el-image v-for="(item, index) in scope.row.headline" :key="index" :src="item" :preview-src-list="[item]" >
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="category_name" label="新闻类别"></el-table-column>
              <el-table-column prop="author" label="新闻作者"></el-table-column>
              <el-table-column prop="price" label="是否置顶轮播">
                <template #default="scope">
                  <el-tag  :type="scope.row.is_banner===1?'primary':'danger'" effect="dark">{{scope.row.is_banner===1?'置顶':'不置顶'}}</el-tag>
                </template>

              </el-table-column>

                <el-table-column label="新闻状态" align="center">
                    <template #default="scope">
                      <el-tag  :type="scope.row.status===0?'success':'danger'" effect="dark">{{scope.row.status===0?'正常':'下架'}}</el-tag>
                    </template>
                </el-table-column>

              <el-table-column width="200px" prop="create_time" label="发布时间"></el-table-column>
              <el-table-column label="操作" width="180" align="center">
                <template #default="scope">
                  <el-button type="text" icon="el-icon-edit" @click="$router.push({name:'news-edit',params:{newsId:scope.row.id}})" >编辑 </el-button>
                  <el-button type="text" icon="el-icon-edit" @click="openNewsDtail(scope.$index, scope.row)" >查看详情 </el-button>
                  <el-button type="text" icon="el-icon-delete" class="red" @click="remove_news(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>

            </el-table>


          <!--   新闻详情弹框      -->
          <el-dialog title="新闻详情
            "v-model="newsDetalSwitch" width="45%" height="75%">
            <div style="border: 1px solid #ccc">
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
            </div>
            <template #footer >
                <span class="dialog-footer" >
                    <el-button @click="newsDetalSwitch = false">关闭</el-button>
                </span>
            </template>
          </el-dialog>


            <div class="pagination">
                <el-pagination background layout="total, prev, sizes, pager, next,jumper"
                               :current-page="query.page+1"
                               :page-size="query.rows"
                               :total="pageTotal"
                               :page-sizes="[5, 10, 20, 50, 100]"
                               @current-change="handlePageChange"
                               @size-change="handleSizeChange"></el-pagination>
            </div>
        </div>
    </div>
</template>



<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 240px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 5px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
